<?php
session_start();
$kuname="jipu";
$table="jipu_item";
$root=preg_replace("/^(.*(yunshop|shante)).*$/Uisx","\\1",getcwd());
include("d:/wwwroot/www/shop/myzhuaqu.php");
header("Access-Control-Allow-Origin: *"); // 允许所有源，或者替换为特定的源
header("Access-Control-Allow-Methods: POST, OPTIONS , GET"); // 允许POST和OPTIONS请求
header("Access-Control-Allow-Headers: Content-Type"); // 允许Content-Type头
use myclass\Sku;

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit;
}

$raw_post_data = file_get_contents('php://input');
$data_post = json_decode($raw_post_data, true);
$pro=array();
$url=$data_post["url"];
$s="";
if(!empty($data_post['arr'])) {
    for ($i = 0; $i < count($data_post['arr']); $i++) {
        $value = preg_replace("/(\n|\r)+/m", "\\n", preg_replace("/^\,/", "", str_replace("'", "\'", $data_post['arr'][$i]["value"])));
        if ($value != "" && $value != "请选择") {
            $s .= trim($data_post['arr'][$i]["name"]) . ":" . $value . "\r\n";
            $pro[trim($data_post['arr'][$i]["name"])]=str_replace("\\n","<p>\n",$value);
        }
    }
}

$url=preg_replace("/(^http[^\?\s\"']+?).*$/Uisx","\\1",$url);
if(preg_match("/shopee\.cn\/portal\/product\/mtsku\/new/i",$url)){
    $set=",shopee='{$s}'";
    $shoptype='shopee';
    $shoptype_num='4';
}
if(preg_match("/weixin\.qq\.com\/shop\/goods\/entry/i",$url)){
    $jsContent=file_get_contents("save_weixin.js");
    $set=",weixin='{$s}'";
    $shoptype='weixin';
    $shoptype_num='3';
}
if(preg_match("/jinritemai\.com\/ffa\/g\/create/i",$url)){
    $jsContent=file_get_contents("save_shopee.js");
    $set=",douyin='{$s}'";
    $shoptype='douyin';
    $shoptype_num='2';
}

if($_REQUEST['item_id']!=""&&$_REQUEST['item_id']!="null") {
    execute("update jipu.jipu_item set protype='{$s}' {$set} where id='{$_REQUEST['item_id']}'");
}else{
    $data=array();
    $data['name']=getValue("商品标题|商品名称");
    $data['subname']=getValue("短标题|商品标签|商品标题");
    $data['summary']=getValue("商品简介|商品描述");
    $data['intro']=getValue("商品详情|商品介绍");
    $data['store_id']=43;
    $store_id=$data['store_id'];
    $data['create_time']=time();

    //处理类别相关
    $sku=new Sku();
    $sku->shoptype($shoptype);
    //处理分类
    $data['category'.$shoptype_num]=getValue("类别");
    $mapId=$sku->clMapCategory($data['category'.$shoptype_num]);
    $sku->clMapOtherShoptypeCategory($mapId);


    //处理图片图集
    $images=newid("jipu.jipu_picture","url",getValue("商品图片和视频|商品详情图集"));
    $data['thumb']=$images[0];
    $data['images']=join(",",$images);

    //处理品牌分类
    $brand_id=newid("jipu.jipu_brand","name",getValue("品牌"));
    if($brand_id[0]!=""){
        $data['brand_id']=$brand_id[0];
    }
    $item_id=insertupdate("jipu.jipu_item",$data,"select id from jipu.jipu_item where name='{$data['name']}'");
    $sku->updateItemCategoryFromMap($item_id,$mapId);
    preg_match("/^.*(\b[0-9]+)/",$sku->category_ids,$nn33);
    $cid=$nn33[1];

    //处理汇总属性集相关
    resetProtype($item_id); //将 douyin,weixin,shopee 的属性 汇总到 protype中

    //处理商品属性和规格
    /*
SELECT *  FROM `jipu_item_property` WHERE id=1
SELECT * FROM `jipu_item_category` WHERE id=52
SELECT * FROM `jipu_property_option` WHERE prp_id=1
SELECT * FROM `jipu_item_specifiction` WHERE item_id=57
SELECT * FROM `jipu_property_option` WHERE `code`='0a9c74'
SELECT * FROM `jipu_property_option` WHERE `code`='db75b7'
     */

    $nn=explode(",",getValue("商品规格"));
    $valuestore="";
    for ($i = 0; $i < count($nn); $i++) {
        $nn2 = explode("#", $nn[$i]);
        $valuestore.=$nn2[1].",";
    }
    $valuestore=substr($valuestore,0,-1);
    for ($i = 0; $i < count($nn); $i++) {
        $nn2 = explode("#", $nn[$i]);
        if($i==0) {
            $data = array();
            $data["cid"] = $cid;
            $data["type"] = "specification";
            $data["store_id"] = $store_id;
            $data["cname"] = $nn2[0];
            $data["formtype"] = "checkbox";
            $data["valuestore"] = $valuestore;
            $data["create_time"] = time();
            $data["update_time"] = $data["create_time"];
            if ($data["cname"] != "" && $data["item_id"] != "") {
                $prp_id = insertupdate("jipu.jipu_item_property", $data, "select id from jipu.jipu_item_property where cname='{$data["cname"]}' and item_id='{$item_id}'");
            }
        }
        $data2=array();
        $data2["code"]=substr(md5($item_id.$nn2[1]),0,6);
        $data2["prp_id"]=$prp_id;
        $data2["option"]=$nn2[1];
        $data2["pic"]=$nn2[2];
        $data2["sort"]=$i+1;
        $option_id = insertupdate("jipu.jipu_property_option", $data2, "select id from jipu.jipu_property_option where code='{$data2["code"]}' and prp_id='{$prp_id}'");
    }

}

function getValue($re){
    global $pro;
    foreach($pro as $name=>$v){
        if(preg_match("/{$re}/Uisx",$name)){
            $v=preg_replace("/\\n/","\n",$v);
            return $v;
        }
    }
    return "";
}
function newid($tablename,$fieldname,$value){
    $nn=explode(",",$value);
    $ids=[];
    $inarr=[];
    for ($i = 0; $i < count($nn); $i++) {
        $data=array();
        $data[$fieldname]=$nn[$i];
        $data['status']=1;
        if($tablename=="jipu.jipu_picture"){
            $data['path']=$data[$fieldname];
            $data['create_time']=time();
        }
        if($nn[$i]!="") {
            $id = insertupdate($tablename, $data, "select id from $tablename where $fieldname='{$nn[$i]}'");
            if (!in_array($id, $inarr)) {
                $ids[] = $id;
            }
        }
    }
    return $ids;
}

/**
 * 将 douyin,weixin,shopee 的属性 汇总到 protype中
 */
function resetProtype($id){
    $rs=getrow("select protype,douyin,weixin,shopee from jipu.jipu_item where id='{$id}'");
    $str=$rs['douyin']."\r\n".$rs['weixin']."\r\n".$rs['shopee'];
    preg_match_all("/^(.*)\:(.*)$/m",$str,$nn);
    $inarr=array();
    $result="";
    for ($i = 0; $i < count($nn[1]); $i++) {
        if(!in_array($nn[1][$i],$inarr)){
            $result.=trim($nn[0][$i])."\n";
        }
    }
    execute("update jipu.jipu_item set protype='".str_replace("'","\'",$result)."' where id='{$id}'");
}

echo json_encode($data_post);